package cn.com.libertymutual.core.http;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;


public class CloseableHttpClientSSL {

	public static HttpComponentsClientHttpRequestFactory acceptsUntrustedCertsHttpClient( int maxTotal, int defaultMaxPerRoute) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

		// setup a Trust Strategy that allows all certificates.
		//
		TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
		SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();


        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
		

        PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager();
		pollingConnectionManager.setMaxTotal( maxTotal );
		pollingConnectionManager.setDefaultMaxPerRoute( defaultMaxPerRoute );
		
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		httpClientBuilder.setConnectionManager(pollingConnectionManager);
		
		
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf).setConnectionManager(pollingConnectionManager)
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();

        requestFactory.setHttpClient(httpClient);
        
        return requestFactory;
	}
}
